package our.pack;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class PhotoDataSource {
	
	private SQLiteDatabase database;
	private DatabaseHelper dbHelper;
	private String[] allColums = { DatabaseHelper.getPhotoID(), DatabaseHelper.getPhotoName(), DatabaseHelper.getPhotoPath(), DatabaseHelper.getPhotoDate(), DatabaseHelper.getPointsID() };
	
	public PhotoDataSource(Context context){
		dbHelper = new DatabaseHelper(context);
	}
	
	/**
	 *  opens the database
	 * @throws SQLException
	 */
	public void open() throws SQLException {
		database = dbHelper.getWritableDatabase();
	}
	
	/**
	 * closes the database
	 */
	public void close() {
		dbHelper.close();
	}
	
	public Photo createPhoto(String photoName, String photoPath, String photoDate, MyPoint point ) {
		ContentValues values = new ContentValues();
		values.put(DatabaseHelper.getPhotoName(), photoName);
		values.put(DatabaseHelper.getPhotoPath(), photoPath);
		values.put(DatabaseHelper.getPhotoDate(), photoDate);
		values.put(DatabaseHelper.getPointsID(), point.getPointsID());
		long instertId = database.insert(DatabaseHelper.getPhotoTable(), null, values);
		Cursor cursor = database.query(DatabaseHelper.getPhotoTable(), allColums, DatabaseHelper.getPhotoID(), null, null, null, null);
		cursor.moveToLast();
		Photo newPhoto = cursorToPhoto(cursor);
		cursor.close();
		return newPhoto;
		}
	
	public void deletePhoto(Photo photo)
	{
		long id = photo.getPhotoID();
		database.delete(DatabaseHelper.getPhotoTable(), DatabaseHelper.getPhotoID() + " = " + id, null);
		
	}
	
	private Photo cursorToPhoto(Cursor cursor){
		Photo photo = new Photo();
		photo.setPhotoID(cursor.getLong(0));
		photo.setPhotoName(cursor.getString(1));
		photo.setPhotoPath(cursor.getString(2));
		photo.setDate(cursor.getString(3));
		photo.setPointsID(cursor.getLong(4));
		return photo;
	}
	
	public ArrayList<Photo> getAllPhotos()
	{
		ArrayList<Photo> photos = new ArrayList<Photo>();
		
		Cursor cursor = database.query(DatabaseHelper.getPhotoTable(), allColums, null, null, null, null, null);
		cursor.moveToFirst();
		while(!cursor.isAfterLast()) {
			Photo photo = cursorToPhoto(cursor);
			photos.add(photo);
			cursor.moveToNext();
		}
		
		cursor.close();
		Log.d("photodatasource", "" + photos.size());
		return photos;
	}
	
	public void removeAllPhotos()
	{
		for( Photo p : getAllPhotos())
		{
//			Photo p = (Photo) m;
			deletePhoto(p);
		}
	}

}
